package org.kaer.election.utils;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.util.Base64;

import java.io.ByteArrayOutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class BitmapStream {

    /**
     * 将bitmap转换成base64字符串
     *
     * @param bitmap
     * @return base64 字符串
     */
    public static String bitmaptoString(Bitmap bitmap, int bitmapQuality) {

        // 将Bitmap转换成字符串
        String string = null;
        ByteArrayOutputStream bStream = new ByteArrayOutputStream();
        bitmap.compress(CompressFormat.PNG, bitmapQuality, bStream);
        byte[] bytes = bStream.toByteArray();
        string = Base64.encodeToString(bytes, Base64.DEFAULT);
        return string;
    }

    public static Bitmap scaleBitmap(Bitmap srcBitmap, int targetWidth, int targetHeight) {
        int srcWidth = srcBitmap.getWidth();
        int srcHeight = srcBitmap.getHeight();
        float sx = targetWidth * 1.0f / srcWidth;
        float sy = targetHeight * 1.0f / srcHeight;
        float s = sx > sy ? sy : sx;
        Matrix m = new Matrix();
        m.setScale(s, s);
        return Bitmap.createBitmap(srcBitmap, 0, 0,srcWidth, srcHeight, m, false);
    }

    /**
     * 将base64转换成bitmap图片
     *
     * @param string base64字符串
     * @return bitmap
     */
    public static Bitmap stringtoBitmap(String string) {
        // 将字符串转换成Bitmap类型
        Bitmap bitmap = null;
        try {
            byte[] bitmapArray;
            bitmapArray = Base64.decode(string, Base64.DEFAULT);
            bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    /* 判斷日期是否在開始時間和結束時間段內 -1 時間格式不合法 0 在時間段內 1选举未开始 2选举已结束 */
    public static int canstart(Date date, String startdate, String enddate) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date startdate4, enddate4;
        try {
            startdate4 = sdf.parse(startdate);
            enddate4 = sdf.parse(enddate);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return -1;
        }
        int result = 0;
        long lstarttime = startdate4.getTime();
        long lenddate = enddate4.getTime();
        long ldate = date.getTime();
        LogUtils.i("date "+date.toString());
        if (ldate < lstarttime) {
            result = 1;
        } else if (ldate > lenddate)
            result = 2;
        return result;
    }

}
